package com.maserb.monitor.web.schoolConduct;

import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.jwOur.JwOurLeaderEntity;
import com.maserb.monitor.entity.schoolConduct.SchoolConductItemEntity;
import com.maserb.monitor.entity.schoolConduct.StudentConductRecordEntity;
import com.maserb.monitor.entity.schoolOrg.SchoolUserOrgEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentParentEntity;
import com.maserb.monitor.model.ContactsModel;
import com.maserb.monitor.model.TeacherCustomModel;
import com.maserb.monitor.repository.schoolOrg.SchoolUserOrgRepository;
import com.maserb.monitor.service.author.AuthorService;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolConduct.SchoolConductItemService;
import com.maserb.monitor.service.schoolConduct.StudentConductRecordService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentParentService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

// AA校园通极光聊天、登录
@RestController
@RequestMapping("/schoolConductApp")
public class SchoolConductAppController {

    @Autowired
    AuthorService authorService;

    @Autowired
    UserService userService;

    @Autowired
    SchoolStudentParentService parentService;

    @Autowired
    StudentConductRecordService studentConductRecordService;

    @Autowired
    SchoolStudentService schoolStudentService;

    @Autowired
    SchoolConductItemService schoolConductItemService;

    @Autowired
    SchoolStudentParentService schoolStudentParentService;

    @Autowired
    SchoolUserOrgRepository userOrgRepository;

    @Autowired
    JwOrgService orgService;

    @Value("${monitor.uploadDir}")
    private String uploadDir;


    public String getUploadDir() {
        return uploadDir;
    }
    //  根据userName,passWord创建用户
    @RequestMapping("/doAddUser")
    @ResponseBody
    public AjaxResult<Boolean> doAddUser(String userName,String passWord,String realName) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                try{
                    JpushImClientUtil.addUser(userName,passWord,realName);
                    return true;
                }catch (Exception e){
                    return false;
                }
            }
        });
    }

    //手机端下载文件
    @RequestMapping("download")
    public String downLoad(HttpServletResponse response, String path){
        String filename = FilenameUtils.concat(getUploadDir(), path);
        File file = new File(filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }



    /**
    * @Description:根据userName,passWord登录，返回用户信息。
    * @Param: [userName, passWord]
    * @return: com.maserb.monitor.common.AjaxResult<com.maserb.monitor.entity.UserEntity>
    * @Author: Mr.Wang
    * @Date: 2018/8/1
    */
    @RequestMapping("/doLoginUser")
    @ResponseBody
    public AjaxResult<UserEntity> doLoginUser(String userName, String passWord,String registrationId) {
        System.out.println("-----------------------------------------------------------");
        System.out.println("-----------------------------------------------------------");
        System.out.println("用户名："+userName);
        System.out.println("密码："+passWord);
        return AjaxUtils.process(new Func_T<UserEntity>() {
            @Override
            public UserEntity invoke() throws Exception {
                if(null==userName && "".equals(userName)){
                    throw new Exception("请输入账号");
                }else{
                    UserEntity userEntity = userService.findByUserName(userName);
                    if(null==userEntity){
                        throw new Exception("账号不存在");
                    }else{
                        if(null!=userEntity.getPassword() && !"".equals(userEntity.getPassword())){
                            if(passWord.equals(userEntity.getPassword())){
                                /*JwOrgEntity clazz = new JwOrgEntity();
                                clazz.setFullName(userEntity.getOrgName());
                                clazz.setName(userEntity.getOrgName());
                                clazz.setId(userEntity.getOrgId());*/
                                /*clazzList.add(clazz);*/
                                userEntity.setLastLoginTime(CreateTimeUtils.getCreateTime());
                                userEntity.setRegistrationId(registrationId);
                                userService.save(userEntity);
                                List<JwOrgEntity> clazzList = new ArrayList<JwOrgEntity>();
                                clazzList = orgService.findByUser(userEntity);
                                if(null!=clazzList && clazzList.size()>0){
                                    userEntity.setClazzList(clazzList);
                                }
                                /*else{
                                    throw new Exception("未发现所属班级，请联系管理员");
                                }*/
                                //标识教师登录
                                userEntity.setType("1");
                                return userEntity;
                            }else{
                                throw new Exception("密码错误");
                            }
                        }
                    }
                }
                return null;
            }
        });
    }

    /**
    * @Description:根据userName,passWord登录，返回家长信息。
    * @Param: [userName, passWord]
    * @return: com.maserb.monitor.common.AjaxResult<com.maserb.monitor.entity.schoolStudent.SchoolStudentParentEntity>
    * @Author: Mr.Wang
    * @Date: 2018/8/1
    */
    @RequestMapping("/doLoginParent")
    @ResponseBody
    public AjaxResult<SchoolStudentParentEntity> doLoginParent(String userName, String passWord,String registrationId) throws Exception{
        System.out.println("-----------------------------------------------------------");
        System.out.println("-----------------------------------------------------------");
        System.out.println("用户名："+userName);
        System.out.println("密码："+passWord);
        return AjaxUtils.process(new Func_T<SchoolStudentParentEntity>() {
            @Override
            public SchoolStudentParentEntity invoke() throws Exception {
                if(null==userName && "".equals(userName)){
                    throw new Exception("请输入账号");
                }else{
                    SchoolStudentParentEntity parentEntity = parentService.findByUserName(userName);
                    if(null==parentEntity){
                        throw new Exception("账号不存在");
                    }else{
                        if(null!=parentEntity.getPassword() && !"".equals(parentEntity.getPassword())){
                            if(passWord.equals(parentEntity.getPassword())){
                                parentEntity.setLoginTime(new Date());
                                parentEntity.setLastLoginTime(CreateTimeUtils.getCreateTime());
                                parentEntity.setRegistrationId(registrationId);
                                parentService.save(parentEntity);
                                List<SchoolStudentEntity>studentList = schoolStudentService.findByParent(parentEntity);
                                if(null!=studentList && studentList.size()>0){
                                    for(SchoolStudentEntity studentEntity:studentList){
                                        studentEntity.setParent(null);
                                        studentEntity.setMaster(null);
                                    }
                                }
                                parentEntity.setStudentList(studentList);
                                //标识家长登录
                                parentEntity.setType("2");
                                return parentEntity;
                            }else{
                                throw new Exception("密码错误");
                            }
                        }
                    }
                }
                return null;
            }
        });
    }


    /**
     * 家长注册
     * @return
     */
    @RequestMapping("/doAddParent")
    @ResponseBody
    public AjaxResult<Boolean> doAddParent(SchoolStudentParentEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                if(org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(entity.getPhoneNumber())){
                    throw new Exception("请输入手机号码！");
                }
                entity.setUserName(entity.getPhoneNumber());
                SchoolStudentParentEntity parentEntity = parentService.findByUserName(entity.getUserName());
                if(null!=parentEntity && null!=parentEntity.getId()&&!"".equals(parentEntity.getId())){
                    throw new Exception("已注册该用户");
                }
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                entity.setSalt(IdUtils.generateId());
                entity.setIsDel("0");
                parentService.save(entity);
                JpushImClientUtil.addUser(entity.getUserName(),entity.getPassword(),entity.getRealName());
                return true;
            }
        });
    }

    /**
     * 根据教师id返回班级
     * @return
     */
    @RequestMapping("/getSchoolUserOrg")
    @ResponseBody
    public AjaxResult<List<SchoolUserOrgEntity>> getSchoolUserOrg(String userId) {
        return AjaxUtils.process(new Func_T<List<SchoolUserOrgEntity>>() {
            @Override
            public List<SchoolUserOrgEntity> invoke() throws Exception {
                UserEntity user = userService.findOne(userId);
                return userOrgRepository.findByUser(user);
            }
        });
    }

    /**
     * 根据家长id返回班级列表
     * @return
     */
    @RequestMapping("/getOrgListByParent")
    @ResponseBody
    public AjaxResult<List<JwOrgEntity>> getOrgListByParent(String parentId) {
        return AjaxUtils.process(new Func_T<List<JwOrgEntity>>() {
            @Override
            public List<JwOrgEntity> invoke() throws Exception {
                SchoolStudentParentEntity parentEntity = parentService.findOne(parentId);
                List<JwOrgEntity>orgList = schoolStudentService.getOrgListByParent(parentEntity);
                return orgList;
            }
        });
    }

    /**
     * 操行规则
     * @return
     */
    @RequestMapping("/conductRuleList")
    @ResponseBody
    public AjaxResult<List<SchoolConductItemEntity>> conductRuleList(String schoolId) {
        return AjaxUtils.process(new Func_T<List<SchoolConductItemEntity>>() {
            @Override
            public List<SchoolConductItemEntity> invoke() throws Exception {
                return schoolConductItemService.findBySchoolId(schoolId);
            }
        });
    }

    /**
     * 学生操行记录
     * @param studentId
     * @return
     */
    @RequestMapping("/conductRecordList")
    @ResponseBody
    public AjaxResult<List<StudentConductRecordEntity>> conductRecordList(String studentId) {
        return AjaxUtils.process(new Func_T<List<StudentConductRecordEntity>>() {
            @Override
            public List<StudentConductRecordEntity> invoke() throws Exception {
                return studentConductRecordService.findByStudent(studentId);
            }
        });
    }

    /**
     * 保存学生操行记录
     * @param studentId
     * @param itemId
     * @return
     */
    @RequestMapping("/saveRecord")
    @ResponseBody
    public AjaxResult<Boolean> saveRecord(String studentId, String itemId, String teacherId,String image,String description) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                if(!StringUtils.isEmpty(studentId) && !StringUtils.isEmpty(itemId)) {
                    StudentConductRecordEntity record = new StudentConductRecordEntity();
                    SchoolStudentEntity student = schoolStudentService.findOne(studentId);
                    SchoolConductItemEntity item = schoolConductItemService.findOne(itemId);
                    UserEntity teacher = userService.findOne(teacherId);
                    record.setCreateTime(new Date());
                    record.setCreateUser(teacher.getRealName());
                    record.setItem(item);
                    record.setStudent(student);
                    record.setImage(image);
                    record.setDescription(description);
                    record.setStatus("0");
                    studentConductRecordService.saveConduct(record);
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 家长联系人
     * @param studentId
     * @return
     */
    @RequestMapping("/parentContacts")
    @ResponseBody
    public AjaxResult<List<ContactsModel>> parentContacts(String studentId) {
        return AjaxUtils.process(new Func_T<List<ContactsModel>>() {
            @Override
            public List<ContactsModel> invoke() throws Exception {
                List<ContactsModel>  contactList = new ArrayList<>();
                if(!StringUtils.isEmpty(studentId)) {
                    SchoolStudentEntity student = schoolStudentService.findOne(studentId);
                    UserEntity master = student.getMaster();
                    ContactsModel model = new ContactsModel();
                    model.setImage(master.getImage());
                    model.setPassword(master.getPassword());
                    model.setPhoneNumber(master.getPhoneNumber());
                    model.setRealName(master.getRealName());
                    model.setUserName(master.getUserName());
                    contactList.add(model);
                }

                return contactList;
            }
        });
    }

    /**
     * 教师联系人
     * @param teacherId
     * @return
     */
    @RequestMapping("/teacherContacts")
    @ResponseBody
    public AjaxResult<List<TeacherCustomModel>> teacherContacts(String teacherId) {
        return AjaxUtils.process(new Func_T<List<TeacherCustomModel>>() {
            @Override
            public List<TeacherCustomModel> invoke() throws Exception {
                List<TeacherCustomModel>  modelList = new ArrayList<>();

                if(!StringUtils.isEmpty(teacherId)) {
                    UserEntity teacher = userService.findOne(teacherId);
                    List<JwOrgEntity> clazzList = new ArrayList<>();
                    /*clazzList.add(clazz);*/
                    List<SchoolUserOrgEntity>userOrgList = userOrgRepository.findByUser(teacher);
                    if(null!=userOrgList && userOrgList.size()>0){
                        Iterator <SchoolUserOrgEntity>iterator = userOrgList.iterator();
                        while(iterator.hasNext()){
                            SchoolUserOrgEntity userOrgEntity = iterator.next();
                            clazzList.add(userOrgEntity.getOrg());
                        }
                    }
                    for(JwOrgEntity clazz : clazzList){
                        System.out.println("-----------------------------------------------");
                        System.out.println("clazz.getId():"+clazz.getId());
                        List<Object[]> objectList = schoolStudentParentService.findObjectByClazzId(clazz.getId());
                        TeacherCustomModel customModel = new TeacherCustomModel();
                        List<ContactsModel> contactsModelList = new ArrayList<ContactsModel>();
                        if(null!=objectList && objectList.size()>0){
                            Iterator <Object[]>iterator = objectList.iterator();
                            while(iterator.hasNext()){
                                    Object[] objects = iterator.next();
                                    SchoolStudentEntity studentEntity = (SchoolStudentEntity)objects[1];
                                    System.out.println("-----------------------------------------------");
                                    System.out.println("studentEntity.getId():"+studentEntity.getId());
                                    SchoolStudentParentEntity parent = (SchoolStudentParentEntity)objects[0];
                                    if(null!=parent){
                                        ContactsModel model = new ContactsModel();
                                        model.setStudentId(studentEntity.getStudentId());
                                        model.setStudentName(studentEntity.getName());
                                        model.setImage(parent.getImage());
                                        model.setPassword(parent.getPassword());
                                        model.setPhoneNumber(parent.getPhoneNumber());
                                        model.setRealName(parent.getRealName());
                                        model.setUserName(parent.getUserName());
                                        contactsModelList.add(model);
                                    }
                            }
                        }
                        customModel.setOrgId(clazz.getId());
                        customModel.setOrgName(clazz.getName());
                        customModel.setModelList(contactsModelList);
                        if(contactsModelList.size()>0){
                            modelList.add(customModel);
                        }
                        /*List<SchoolStudentParentEntity> parentList = schoolStudentParentService.findAll(clazz.getId());
                        for(SchoolStudentParentEntity parent : parentList) {
                            ContactsModel model = new ContactsModel();
                            model.setImage(parent.getImage());
                            model.setPassword(parent.getPassword());
                            model.setPhoneNumber(parent.getPhoneNumber());
                            model.setRealName(parent.getName());
                            model.setUserName(parent.getUserName());
                            contactList.add(model);
                        }*/
                    }
                }
                return modelList;
            }
        });
    }

    //App Store 隐私政策
    @RequestMapping("/appStoreView")
    public ModelAndView view(){
        ModelAndView result = new ModelAndView();
        result.setViewName("jw_our/our_view");
        return  result;
    }
}
